//
//  HomeViewController.swift
//  波波微博上传
//
//  Created by wave on 15/7/27.
//  Copyright © 2015年 wave. All rights reserved.
//

import UIKit

class HomeViewController: BaseViewController {

    var statuses:[Status]?{
        didSet{
        
            //刷新数据
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        
        if !UserAccount.userLogn{
            visitorView?.setupViewInfo(true, title: "关注一些人，回这里看看有什么惊喜", imageName: "visitordiscover_feed_image_house")
        
            return
        }
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPicture:", name: BBBPicCellSelectNotify, object: nil)
        
        loadData()
        
        tableviewStyle()
    }
    deinit{
        
        //注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: - 通知监听方法
    @objc private func selectPicture(n:NSNotification){
        //获取参数
        //urls
        guard let urls = n.userInfo![BBBPicCellSelectUrlKey] as? [NSURL] else{
            
            print("URL数组不存在")
            return
        }
        //下标index
        guard let indexPath = n.userInfo![BBBPicCellSelectIndexKey] as? NSIndexPath else{
            
            print("indexPath不存在")
            return
        }
    
        let vc = PhotoBrowserViewVC(urls:urls , selectedIndex: indexPath.item)
        
        vc.transitioningDelegate = self
        
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    //设置tableview的一些style
    private func tableviewStyle(){
    
        //注册原型, rawValue返回枚举对应实际数值
        tableView.registerClass(StatusNomalCell.self, forCellReuseIdentifier: StatusCellIdentifier.NormalCell.rawValue)
        tableView.registerClass(StatusForwarCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)
        
//        //行高
        //设置表格预估行高(方便表格提前计算预估行高,提高性能) - 尽量准确,能够提高性能
        tableView.estimatedRowHeight = 300
        //设置表格自动计算行高
//        tableView.rowHeight = UITableViewAutomaticDimension
        //取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //刷新控件,高度默认是60
        refreshControl = BBBRefreshControl()
        
        //添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        
    }

    //加载数据
    //上拉刷新的标记
    private var pullRefreshMark = false
    func loadData(){
            
        refreshControl?.beginRefreshing()
        
        //刷新新数据,获取到数组中第一条记录的id
        //第一次执行此方法的时候,statuses为空since_id = 0,加载最新的20条记录
        var since_id = statuses?.first?.id ?? 0
        var max_id = 0
        
        if pullRefreshMark{
        
            since_id = 0
            //记录数组最后一条记录的id
            max_id = statuses?.last?.id ?? 0
        }
        
        //                  这里加个weak self是为了防止循环引用,在下边的self?.statuses这里也要加个?号
        Status.loadStatus (since_id,max_id:max_id){(dataList, error) -> () in
            
            //关闭刷新控件,结束刷新动画
            self.refreshControl?.endRefreshing()
            
            //复位上拉刷新标记,保证下一次仍然能够上拉
            self.pullRefreshMark = false
            
            if error != nil{
                print(error)
                return
            }
            
            let count = dataList?.count ?? 0
            print("刷新到\(count) 条数据")
            
            if since_id > 0{
                
                self.showPulldownTip(count)
            }

            //如果没有数据,直接返回
            if count == 0{
                
                return
            }
            
            if since_id > 0{
                
                //下拉刷新,应该将结果集合放在之前数组的前边
                self.statuses = dataList! + self.statuses!
            }else if max_id > 0{
                //上拉刷新,应该将结果集合放在数组的后面
                self.statuses! += dataList!
            }else{
                self.statuses = dataList
            }
            
            
        }
    }
    
    //MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        
        //要求必须注册原型cell,storyboard,register,Class
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status), forIndexPath: indexPath) as! StatusCell

        //判断indexPatch的数值
        if indexPath.row == statuses!.count - 1{
            
            //设置上拉刷新标记
            pullRefreshMark = true
            
            loadData()
        }
        cell.status = statuses![indexPath.row]
        
        return cell
    }
    
    //返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        //判断模型中,是否已经缓存了行高
        let status = statuses![indexPath.row]
        
        if let h = status.rowHeigth{
//            print("返回缓存行高")
            
            return h
        }
        /*
        思路:
            1.获取cell
            2.获取模型
            3.反回行高
        */
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status)) as? StatusCell
        
        status.rowHeigth = cell!.rowHeight(status)
        
        return status.rowHeigth!
        
    }
    
    
    //显示下拉刷新的数据条数
    private func showPulldownTip(count:Int){
    
        //定义标签文字
        tipLabel.text = (count == 0) ? "暂时没有新的微博" : "刷新到\(count)条微博"
//        if count == 0{
//            tipLabel.text == "暂时没有新的微博"
//        }else{
//            tipLabel.text == "刷新到\(count)条微博"
//        }
        
        //表现的初始位置
        let rect = tipLabel.frame
        
        //做个滚动动画
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            //自动反转动画
            UIView.setAnimationRepeatAutoreverses(true)
            
            //移动label的位置
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
            //将标签复位
            self.tipLabel.frame = rect
        }
            
        print(view)
        print(tableView)
    }
    
    //懒加载
    private lazy var tipLabel: UILabel = {
        let h:CGFloat = 44
        let label = UILabel(frame: CGRect(x: 0, y: -2 * h, width:self.view.bounds.width, height: h))
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        
        //将label添加到界面,将label加载到navBar上边,不会随着tableView一起滚动
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        return label
        }()
    
    //是否是Modal展现的标记
    private var isPresent = false
}

//转场协议
extension HomeViewController:UIViewControllerTransitioningDelegate{

    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresent = true
        
        return self
    }
    
    //返回提示接触转场动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresent = false
        
        return self
    }
    
}
//自定义转场动画
extension HomeViewController:UIViewControllerAnimatedTransitioning{
    
    //转场动画
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        
        return 0.5
    }
    
    //自定义转场动画,如果实现了自定义转场方法,就必须自己实现转场动画代码
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let formVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        print(formVC)
        print(toVC)
        
        //Modal
        if isPresent{
            
            //展现视图
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            //将目标视图添加到容器视图中
            transitionContext.containerView()?.addSubview(toView)
            toView.alpha = 0
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                toView.alpha = 1.0
                }) { (_) -> Void in
                    
                    transitionContext.completeTransition(true)
            }
            
        }else{
            
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                fromView.alpha = 0.0
                
                }, completion: { (_) -> Void in
                    
                    fromView.removeFromSuperview()
                    
                    transitionContext.completeTransition(true)
            })

        }
        
    }
}





